package com.zhongshengnetwork.rightbe.game.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dd.CircularProgressButton;
import com.google.gson.JsonObject;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.HandlerDefine;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.game.model.PKMessage;
import com.zhongshengnetwork.rightbe.game.view.PKPopWindow;
import com.zhongshengnetwork.rightbe.game.view.WaveView;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKMsgModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKRoomModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKRuleModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKUserModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangDetailActivity;

import java.util.HashMap;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

public class PrePKActivity extends AppBaseActivity {
    private PKPopWindow pkPopWindowLeft;
    private PKPopWindow pkPopWindowRight;

    private WaveView prepk_wave;
    private CircularProgressButton prepk_bg;
    private ImageView prepk_header;
    private TextView prepk_nickname;
    private TextView prepk_area;
    private TextView prepk_level;
    private TextView prepk_fee;
    private RelativeLayout prepk_main;
    private LinearLayout prepk_des;
    private RelativeLayout prepk_view;

    private int fee;
    private int type;
    private String code;

    private PKRoomModel pkRoomModel;
    private PKRuleModel pkRuleModel;
    private PKUserModel pkUserModel = null;
    private PKUserModel anotherPKUserModel;
    private PKUserModel roleUserModel;
    private String mData = null;

    private CountDownTime mTime;
    private boolean isTimeOut = false;
    private boolean isReady = false;
    private boolean isBack = false;

    public MyHandler myHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_pk);
        //注册广播
        registerBoradcastReceiver();
        myHandler = new MyHandler();
        Intent intent = this.getIntent();
        pkUserModel = (PKUserModel) intent.getSerializableExtra("pkuser");
        fee = intent.getIntExtra("fee",0);
        type = intent.getIntExtra("type",0);
        code = intent.getStringExtra("code");

        prepk_main = (RelativeLayout)findViewById(R.id.prepk_main);
        prepk_des = (LinearLayout)findViewById(R.id.prepk_des);
        prepk_view = (RelativeLayout)findViewById(R.id.prepk_view);
        prepk_wave = (WaveView) findViewById(R.id.prepk_wave);
        prepk_wave.setColor(Color.parseColor("#00BFFF"));

        prepk_bg = (CircularProgressButton)findViewById(R.id.prepk_bg);
        prepk_bg.setBackgroundColor(getResources().getColor(R.color.mainColor));
        prepk_bg.setStrokeColor(getResources().getColor(R.color.mainColor));

        prepk_header = (ImageView)findViewById(R.id.prepk_header);
        prepk_nickname = (TextView)findViewById(R.id.prepk_nickname);
        prepk_area = (TextView)findViewById(R.id.prepk_area);
        prepk_level = (TextView)findViewById(R.id.prepk_level);
        prepk_fee = (TextView)findViewById(R.id.prepk_fee);
        Glide.with(PrePKActivity.this).load(pkUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(PrePKActivity.this)).dontAnimate().into(prepk_header);
        prepk_nickname.setText(pkUserModel.getNickname());
        if (!CommonUtils.isEmpty(pkUserModel.getArea())){
            prepk_area.setText("来自："+pkUserModel.getArea());
        }
        prepk_level.setText("Lv."+pkUserModel.getPlaylevel());
        prepk_fee.setText("入场金币："+fee);

        prepk_wave.start();

        pkPopWindowLeft = new PKPopWindow(PrePKActivity.this,0);
        pkPopWindowRight = new PKPopWindow(PrePKActivity.this,1);

        pkPopWindowLeft.pk_pop_left_window_bg.setBackgroundColor(getResources().getColor(R.color.limitBackgroundColor));
        pkPopWindowLeft.pk_pop_left_window_bg.setStrokeColor(getResources().getColor(R.color.limitBackgroundColor));
        pkPopWindowLeft.pk_pop_left_window_circle.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pkPopWindowLeft.pk_pop_left_window_circle.setStrokeColor(getResources().getColor(R.color.mainColor));
        Glide.with(PrePKActivity.this).load(pkUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(PrePKActivity.this)).dontAnimate().into(pkPopWindowLeft.pk_pop_left_window_header);
        pkPopWindowLeft.pk_pop_left_window_nickname.setText(pkUserModel.getNickname());
        if (!CommonUtils.isEmpty(pkUserModel.getArea())){
            pkPopWindowLeft.pk_pop_left_window_area.setText("来自："+pkUserModel.getArea());
        }else {
            pkPopWindowLeft.pk_pop_left_window_area.setText("");
        }
        pkPopWindowLeft.pk_pop_left_window_level.setText("Lv."+pkUserModel.getPlaylevel());
        pkPopWindowLeft.pk_pop_left_window_fee.setText("入场金币："+fee);

        pkPopWindowRight.pk_pop_right_window_bg.setBackgroundColor(getResources().getColor(R.color.wordBgColor));
        pkPopWindowRight.pk_pop_right_window_bg.setStrokeColor(getResources().getColor(R.color.wordBgColor));
        pkPopWindowRight.pk_pop_right_window_circle.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pkPopWindowRight.pk_pop_right_window_circle.setStrokeColor(getResources().getColor(R.color.mainColor));

        getData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void back(){
        isBack = true;
        prepk_wave.stop();
        leaveRoom("0");
        finish();
    }

    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            System.out.println("按下了back键   onKeyDown()");
            back();
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }

    public void onClickBack(View view){
        back();
    }

    //离开房间
    private void leaveRoom(String type){
        if (pkRoomModel != null){
            String url = "miniapp/pkappid/quitpk.do";
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put(APIKey.typeKey,type);
            map.put(APIKey.idKey,pkRoomModel.getId()+"");
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {

                }

                @Override
                public void onError(String msg) {

                }
            });
        }
    }

    private void pkReady(final boolean isGet){
        if (isBack == true){
            return;
        }
        if (isReady == true){
            return;
        }
        isReady = true;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //unregisterReceiver(mBroadcastReceiver);
                stopTime();
                prepk_wave.stop();
                prepk_wave = null;
                updatePKState();
                prepk_main.setVisibility(View.GONE);
                prepk_des.setVisibility(View.GONE);

                if (anotherPKUserModel == null){

                    Glide.with(PrePKActivity.this).load(roleUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(PrePKActivity.this)).dontAnimate().into(pkPopWindowRight.pk_pop_right_window_header);
                    pkPopWindowRight.pk_pop_right_window_nickname.setText(roleUserModel.getNickname());
                    if (!CommonUtils.isEmpty(roleUserModel.getArea())){
                        pkPopWindowRight.pk_pop_right_window_area.setText("来自："+roleUserModel.getArea());
                    }else {
                        pkPopWindowRight.pk_pop_right_window_area.setText("");
                    }
                    pkPopWindowRight.pk_pop_right_window_level.setText("Lv."+roleUserModel.getPlaylevel());
                    pkPopWindowRight.pk_pop_right_window_fee.setText("入场金币："+fee);


                    Log.e("TAG","姓名："+roleUserModel.getNickname());

                }else {
                    Glide.with(PrePKActivity.this).load(anotherPKUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(PrePKActivity.this)).dontAnimate().into(pkPopWindowRight.pk_pop_right_window_header);
                    pkPopWindowRight.pk_pop_right_window_nickname.setText(anotherPKUserModel.getNickname());
                    if (!CommonUtils.isEmpty(anotherPKUserModel.getArea())){
                        pkPopWindowRight.pk_pop_right_window_area.setText("来自："+anotherPKUserModel.getArea());
                    }else {
                        pkPopWindowRight.pk_pop_right_window_area.setText("");
                    }
                    pkPopWindowRight.pk_pop_right_window_level.setText("Lv."+anotherPKUserModel.getPlaylevel());
                    pkPopWindowRight.pk_pop_right_window_fee.setText("入场金币："+fee);
                }

                if (isGet == true){
                    pkPopWindowLeft.showAtLocation(prepk_view,
                            Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0);
                    pkPopWindowRight.showAtLocation(prepk_view,
                            Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0);
                }else {
                    pkPopWindowRight.showAtLocation(prepk_view,
                            Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0);
                    pkPopWindowLeft.showAtLocation(prepk_view,
                            Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0);
                }


                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(PrePKActivity.this,PKActivity.class);
                        intent.putExtra(APIKey.dataKey,mData);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("pkuser", pkUserModel);//序列化
                        if (anotherPKUserModel == null){
                            bundle.putSerializable("roleuser",roleUserModel);
                        }else {
                            bundle.putSerializable("anotherpkuser",anotherPKUserModel);
                        }
                        bundle.putSerializable("pkrule",pkRuleModel);
                        bundle.putSerializable("pkroom",pkRoomModel);
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                        finish();
                    }
                }, pkRuleModel.getPkshowanswertime()*1000);
            }
        });

    }

    private void getData(){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put(APIKey.typeKey,type+"");
        map.put(APIKey.codeKey,code);
        String url = "miniapp/"+"pkappid"+"/enterpk.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","数据="+data+"\n");
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    mData = data;
                   pkRoomModel = GsonTools.getPKRoomModel(data);
                    pkRuleModel = GsonTools.getPKRuleModel(data);
                    roleUserModel = GsonTools.getPKRoleUserModel(data);
                    if (pkRoomModel.getStatus() == 1 && !CommonUtils.isEmpty(pkRoomModel.getAcceptUserid())){
                        anotherPKUserModel = GsonTools.getAnotherPKUserModel(data);
                        PKMsgModel model = new PKMsgModel();
                        model.setRoomID(pkRoomModel.getId());
                        model.setName(PKMsgModel.PKReady);
                        model.setTime(2);
                        model.setAppid(CommonUtils.formatString(pkUserModel.getAppid()));
                        model.setGoldcount(fee);
                        model.setHeader(pkUserModel.getHeader());
                        model.setLevelName(CommonUtils.formatString(pkUserModel.getLevelName()));
                        model.setNickname(pkUserModel.getNickname());
                        model.setPlaylevel(pkUserModel.getPlaylevel());
                        model.setRole(pkUserModel.getRole());
                        model.setUserid(pkUserModel.getUserid());
                        model.setTargetId(pkRoomModel.getSendUserid());
                        sendPKNotify(model);
                        pkReady(true);
                    }else {
                        if (CommonUtils.isEmpty(code)){
                            startTime();
                        }
                    }
                }else {
                    CustomApplication.showTip(commonModel, PrePKActivity.this);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void updatePKState(){
        if (pkRoomModel != null){
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put(APIKey.idKey,pkRoomModel.getId()+"");
            String url = "miniapp/"+"pkappid"+"/updatepkroom.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {

                }

                @Override
                public void onError(String msg) {

                }
            });
        }

    }

    /**
     * 第一种方法 使用android封装好的 CountDownTimer
     * 创建一个类继承 CountDownTimer
     */
    class CountDownTime extends CountDownTimer {

        //构造函数  第一个参数代表总的计时时长  第二个参数代表计时间隔  单位都是毫秒
        public CountDownTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) { //每计时一次回调一次该方法
            //guess_word_level.setText("倒计时:"+l/1000+"秒");
        }

        @Override
        public void onFinish() { //计时结束回调该方法
            if (isBack == true){
                return;
            }
            isTimeOut = true;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pkReady(false);
                }
            });
        }
    }

    private void startTime(){
        if (pkRoomModel == null){
            return;
        }
        if (mTime != null){
            mTime.cancel();
            mTime = null;
        }
        isTimeOut = false;
        mTime = new CountDownTime(pkRuleModel.getPkwaittimeOut()*1000, 1000);//初始化对象
        mTime.start();
    }

    private void stopTime(){
        if (pkRoomModel == null){
            return;
        }
        if (mTime != null){
            mTime.cancel();
            mTime = null;
        }
    }

    class MyHandler extends Handler {
        //默认构造函数
        public MyHandler(){
            super();
        }

        //带有Looper参数的构造函数
        public MyHandler(Looper L){
            super(L);
        }

        //子类重写次方法，处理消息

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg == null || msg.obj == null){
                return;
            }
            if (msg.obj.toString().equals(HandlerDefine.pkmsg)){
                pkReady(false);
            }
        }
    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.print("onReceive接收到广播了" + "\n");
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.PKMsg)){
                String content = intent.getStringExtra(APIKey.contentKey);
                PKMsgModel pkMsgModel = GsonTools.getPKMsgModel(content);
                if (pkMsgModel.getName().equals(PKMsgModel.PKReady)){
                    stopTime();
                    anotherPKUserModel = new PKUserModel();
                    anotherPKUserModel.setAppid(pkMsgModel.getAppid());
                    anotherPKUserModel.setArea(CommonUtils.formatString(pkMsgModel.getArea()));
                    anotherPKUserModel.setGoldcount(pkMsgModel.getGoldcount());
                    anotherPKUserModel.setHeader(pkMsgModel.getHeader());
                    anotherPKUserModel.setNickname(pkMsgModel.getNickname());
                    anotherPKUserModel.setLevelName(pkMsgModel.getLevelName());
                    anotherPKUserModel.setPlaylevel(pkMsgModel.getPlaylevel());
                    anotherPKUserModel.setRole(pkMsgModel.getRole());
                    anotherPKUserModel.setUserid(pkMsgModel.getUserid());

                    Message msg = new Message();
                    msg.obj = new String(HandlerDefine.pkmsg);
                    myHandler.sendMessage(msg);
                }

            }
        }
    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.PKMsg);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private void sendPKNotify(PKMsgModel pkMsgModel){
        JsonObject userinfo = new JsonObject();
        userinfo.addProperty(APIKey.useridKey,CustomApplication.loginModel.getUid());
        userinfo.addProperty(APIKey.nameKey,CustomApplication.loginModel.getNickname());
        userinfo.addProperty(APIKey.portraituriKey,CustomApplication.loginModel.getThumbheader());

        JsonObject content = new JsonObject();
        content.addProperty(APIKey.nameKey,pkMsgModel.getName());
        content.addProperty(APIKey.timeKey,pkMsgModel.getTime()+"");
        content.addProperty("goldcount",pkMsgModel.getGoldcount()+"");
        content.addProperty(APIKey.headerKey,pkMsgModel.getHeader());
        content.addProperty(APIKey.nicknameKey,pkMsgModel.getNickname());
        content.addProperty("playlevel",pkMsgModel.getPlaylevel()+"");
        content.addProperty("role",pkMsgModel.getRole()+"");
        content.addProperty(APIKey.useridKey,pkMsgModel.getUserid());
        content.addProperty("roomID",pkMsgModel.getRoomID()+"");

        PKMessage pkMessage = new PKMessage(content.toString(),userinfo.toString());
        final io.rong.imlib.model.Message message = io.rong.imlib.model.Message.obtain(pkMsgModel.getTargetId(), Conversation.ConversationType.PRIVATE, pkMessage);
        message.setSenderUserId(CustomApplication.loginModel.getUid());
        message.setSentStatus(io.rong.imlib.model.Message.SentStatus.SENDING);
        message.setMessageDirection(io.rong.imlib.model.Message.MessageDirection.SEND);
        String pushData = "";


        RongIMClient.getInstance().sendMessage(message, pushData, "", new RongIMClient.SendMessageCallback() {
            @Override
            public void onSuccess(Integer arg0) {
                message.setSentStatus(io.rong.imlib.model.Message.SentStatus.SENT);// 已发送
                RongIMClient.getInstance().getMessage(arg0, new RongIMClient.ResultCallback<io.rong.imlib.model.Message>() {
                    @Override
                    public void onSuccess(io.rong.imlib.model.Message message) {

                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }

            @Override
            public void onError(Integer arg0, RongIMClient.ErrorCode arg1) {
                message.setSentStatus(io.rong.imlib.model.Message.SentStatus.FAILED);// 发送失败
                RongIMClient.getInstance().getMessage(arg0, new RongIMClient.ResultCallback<io.rong.imlib.model.Message>() {
                    @Override
                    public void onSuccess(io.rong.imlib.model.Message message) {

                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }
        }, new RongIMClient.ResultCallback<io.rong.imlib.model.Message>() {
            @Override
            public void onSuccess(final io.rong.imlib.model.Message message) {

            }

            @Override
            public void onError(RongIMClient.ErrorCode arg0) {

            }
        });

    }

}
